﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SqlExecuteHelper
{
    public delegate void ConfigEventHandler(string serverName,string serverIp,string password);
    
    public partial class ConfigForm : Form
    {
        //窗体确定事件
        public event ConfigEventHandler ConfirmEvent;           
        private string DefaultPassword { get { return "OpenSWITCH888"; } }
        private string DefaultPort { get { return "1433"; } }
        private string DefaultServerName { get { return "MSSQLSERVER"; } }

        public ConfigForm()
        {
            InitializeComponent();
            this.txtPort.Text = DefaultPort;
            this.txtPassword.Text = DefaultPassword;
            this.txtServerName.Text = DefaultServerName;
        }

        public ConfigForm(string name, string address, string password)
        {
            InitializeComponent();
            var port = DefaultPort;
            var serverName = DefaultServerName;
            if (address.Contains(","))
            {
                port = address.Split(',')[1];
                address = address.Split(',')[0];
                if (address.Contains('\\'))
                {
                    serverName = address.Split('\\')[1];
                    address = address.Split('\\')[0];                    
                }
            }
            this.txtName.Text = name;
            this.txtAddress.IP = address;
            this.txtPassword.Text = password;
            this.txtPort.Text = port;
            this.txtName.Enabled = false;
            this.txtServerName.Text = serverName;
            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string name = this.txtName.Text;
            string address = this.txtAddress.IP;
            string port = this.txtPort.Text; 
            string serverName = this.txtServerName.Text;
            string password = string.IsNullOrEmpty(this.txtPassword.Text) ? DefaultPassword : this.txtPassword.Text;
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("请输入名称！");
                return;
            }
            if (string.IsNullOrEmpty(address))
            {
                MessageBox.Show("请输入服务器地址！");
                return;
            }
            if (!string.IsNullOrEmpty(serverName))
            {
                address = address + "\\" + serverName;
            }
            if (!string.IsNullOrEmpty(this.txtPort.Text))
            {
                address = address + "," + port;
            }

            this.ConfirmEvent(name, address, password);

            this.Close();
        }
    }
}
